<!--
 * @Author: your name
 * @Date: 2021-01-26 16:32:24
 * @LastEditTime: 2021-01-29 16:10:37
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \tlwok-front-purchase-platfrom\src\pages\admin\purchase\goods.vue
-->
<template>
  <div>
    <div class="flex-box">
      <div class="lf">
        <el-button
          type="primary"
          size="medium"
          icon="el-icon-plus"
          @click="editGoods()"
          >添加采购商品</el-button
        >
      </div>
      <div class="rt">
        <el-button @click="onExportExcel()" type="primary" size="medium"
          >下载导入模板</el-button
        >
        <el-upload
          style="display: inline-block; margin: 0 10px"
          name="file"
          action=""
          accept=".xls,.xlsx"
          :http-request="onImportItem"
          :show-file-list="false"
        >
          <el-button
            :loading="importItemLoading"
            type="primary"
            plain
            size="medium"
            icon="el-icon-upload2"
            >批量导入采购商品</el-button
          >
        </el-upload>
      </div>
    </div>
    <div class="table-box">
      <div class="table-title">
        <span class="title">
          <i class="el-icon-notebook-2 el-icon--left"></i>采购商品列表
        </span>
        <div>
          <el-button
            type="primary"
            size="mini"
            :disabled="!selection.length"
            @click="onBatchDelete()"
          >
            批量删除
          </el-button>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        border
        :header-cell-style="tableHeaderColor"
        :cell-style="tableCellStyle"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="name" label="商品名称"> </el-table-column>
        <el-table-column prop="commodityCategory" label="商品类目" width="300">
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="200">
        </el-table-column>
        <el-table-column prop="attribute" label="规格型号" width="250">
        </el-table-column>
        <el-table-column label="参考价（元）" width="200">
          <template slot-scope="scope">
            <span class="red">
              {{ scope.row.referencePrice | formatAmount }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="商品图片" width="150">
          <template slot-scope="scope">
            <el-avatar
              shape="square"
              :size="100"
              :src="scope.row.picUrl"
            ></el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-link type="primary" @click="editGoods(scope.row)">编辑</el-link>
            <el-popconfirm
              title="确认删除该商品？"
              @confirm="onDelete(scope.row.id)"
            >
              <el-link slot="reference" type="primary">删除</el-link>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-handler">
        <div></div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageIndex"
          :page-sizes="pageSizeArr"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </div>

    <el-dialog
      :title="onEditGoods ? '编辑商品' : '添加商品'"
      :visible.sync="goodsDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="goodsFormData"
        :rules="goodsFormRules"
        ref="goodsForm"
        class="purchaseGoodsForm"
      >
        <el-form-item
          label="商品名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input
            type="textarea"
            v-model.trim="goodsFormData.name"
            placeholder="请输入商品名称"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="商品类目"
          :label-width="formLabelWidth"
          prop="cids"
        >
          <el-cascader
            v-model="goodsFormData.cids"
            :options="categoryOptions"
            @change="categoryChange"
            :props="{ value: 'id', label: 'name', children: 'children' }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="品牌" :label-width="formLabelWidth" prop="brand">
          <el-input
            v-model.trim="goodsFormData.brand"
            placeholder="请输入品牌"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="规格型号"
          :label-width="formLabelWidth"
          prop="attribute"
        >
          <el-input
            v-model.trim="goodsFormData.attribute"
            placeholder="请输入规格型号"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="参考价(元)"
          :label-width="formLabelWidth"
          prop="referencePrice"
        >
          <el-input
            type="digit"
            v-model.trim="goodsFormData.referencePrice"
            placeholder="请输入参考价"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="商品图片"
          :label-width="formLabelWidth"
          prop="picUrl"
        >
          <el-upload
            class="purchaseGoodsForm"
            name="file"
            action=""
            accept="image/*"
            :http-request="$event => uploadGoodsImage($event, goodsFormData)"
            :show-file-list="false"
          >
            <img
              v-if="goodsFormData.picUrl"
              :src="goodsFormData.picUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus purchaseGoodsForm-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="goodsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitGoodsFormData('goodsForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  pageList,
  batchDelete,
  deleteGoods,
  batchImport,
  uploadGoodsImage,
  add,
  update,
} from '@/api/purchase/goods'
import { categoryList } from '@/api/category'

export default {
  data() {
    return {
      total: 0,
      pageSizeArr: [10, 20, 30, 40],
      pageSize: 10, // 分页页面数量大小
      pageIndex: 1, // 开始页码
      tableData: [],
      selection: [],
      importItemLoading: false,
      goodsDialogVisible: false,
      formLabelWidth: '100px',
      goodsFormData: {
        name: null,
        brand: null,
        cids: [],
        attribute: null,
        referencePrice: null,
        picUrl: null,
      },
      onEditGoods: false,
      onEditGoodsId: null,
      goodsFormRules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        cids: {
          type: 'array',
          required: true,
          message: '请选择商品类目',
          asyncValidator: (rule, value) => {
            return new Promise((resolve, reject) => {
              if (value.length < 1) {
                reject('请选择商品类目')
              } else {
                resolve()
              }
            })
          },
        },
        brand: [{ required: true, message: '请输入品牌', trigger: 'blur' }],
        attribute: [
          { required: true, message: '请输入规格型号', trigger: 'blur' },
        ],
        referencePrice: [
          { required: true, message: '请输入参考价', trigger: 'blur' },
          {
            pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
            message: '参考价格式不正确',
          },
        ],
        picUrl: [{ required: true, message: '请上传商品图片' }],
      },
      categoryOptions: [],
    }
  },
  methods: {
    // 修改table header的背景色
    tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      return 'background-color: #f5f5f5;color: #333;font-weight: bold;text-align:center'
    },
    // 修改table tr行的样式
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      return 'text-align:center'
    },
    // 分页数量大小设置
    handleSizeChange(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getList()
    },
    // 分页当前页设置
    handleCurrentChange(val) {
      this.pageIndex = val
      this.getList()
    },
    async getList() {
      const loading = this.$loading()
      try {
        const { total, list } = await pageList({
          pageSize: this.pageSize,
          pageIndex: this.pageIndex,
        })
        this.total = total
        this.tableData = list
      } catch (error) {
        console.log(error)
      }
      loading.close()
    },
    handleSelectionChange(val) {
      this.selection = val
    },
    async onBatchDelete() {
      const loading = this.$loading()
      try {
        await batchDelete({
          idList: this.selection.map(item => item.id),
        })
        this.$message.success('批量删除成功')
        this.getList()
      } catch (error) {
        console.log(error)
      }
      loading.close()
    },
    async onDelete(id) {
      const loading = this.$loading()
      try {
        await deleteGoods(id)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        console.log(error)
      }
      loading.close()
    },
    onExportExcel() {
      window.open(
        'https://oss.tlwok.com/%E9%87%87%E8%B4%AD%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls'
      )
    },
    async onImportItem(param) {
      this.importItemLoading = true
      try {
        await batchImport(param.file)
        this.$message.success(`导入成功`)
        this.getList()
      } catch (error) {
        console.error(error)
      }
      this.importItemLoading = false
    },
    editGoods(row) {
      Object.keys(this.goodsFormData).map(key => {
        if (key === 'cids') this.goodsFormData['cids'] = []
        else this.goodsFormData[key] = null
      })
      this.onEditGoods = false
      this.onEditGoodsId = null

      if (row) {
        this.onEditGoods = true
        this.onEditGoodsId = row.id
        Object.keys(this.goodsFormData).map(key => {
          if (key === 'cids') {
            this.goodsFormData.cids = [row.cidLev1, row.cidLev2, row.cidLev3]
          } else this.goodsFormData[key] = row[key] || null
        })
      }
      this.goodsDialogVisible = true
    },
    async getCategoryList() {
      this.categoryOptions = await categoryList()
    },
    categoryChange() {},
    submitGoodsFormData(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) return false

        let param = {
          name: null,
          brand: null,
          cidLev1: null,
          cidLev2: null,
          cidLev3: null,
          attribute: null,
          referencePrice: null,
          picUrl: null,
        }
        Object.keys(this.goodsFormData).map(key => {
          if (key === 'cids') {
            param.cidLev1 = this.goodsFormData.cids[0]
            param.cidLev2 = this.goodsFormData.cids[1]
            param.cidLev3 = this.goodsFormData.cids[2]
          } else {
            if (this.goodsFormData[key]) param[key] = this.goodsFormData[key]
          }
        })
        this._submitGoodsFormData(param)
      })
    },

    async _submitGoodsFormData(param) {
      if (this.onEditGoods) {
        param.id = this.onEditGoodsId
        try {
          await update(param)
          this.$message.success('编辑成功')
          this.goodsDialogVisible = false
          this.getList()
        } catch (error) {
          console.log(error)
        }
      } else {
        try {
          await add(param)
          this.$message.success('添加成功')
          this.goodsDialogVisible = false
          this.getList()
        } catch (error) {
          console.log(error)
        }
      }
    },

    async uploadGoodsImage(param, row) {
      const loading = this.$loading()
      try {
        const result = await uploadGoodsImage(param.file)
        row.picUrl = result
      } catch (error) {
        console.error(error)
      }
      loading.close()
    },
  },
  created() {
    this.getCategoryList()
  },
  mounted() {
    this.getList()
  },
}
</script>

<style scoped lang="scss">
.flex-box {
  display: flex;
  justify-content: space-between;
}
.table-title {
  height: 47px;
  line-height: 47px;
  padding: 0 15px;
  display: flex;
  justify-content: space-between;
}
.table-box {
  border: 1px solid #ddd;
  margin-top: 10px;
}
.table-handler {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
}
</style>
<style lang="scss">
.purchaseGoodsForm {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409eff;
  }
  .purchaseGoodsForm-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
}
</style>
